from django.shortcuts import render

# Create your views here.

# from alipay import AliPay
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView

from orders.models import OrderInfo
from mall import settings
from .utils import Generate_alipay_handler
from .models import Payment

class OrdersALIPayView(APIView):

    def get(self,request,order_id):
        # 思路:
        # 判断订单是否正确
        # 创建支付对象
        # 调用支付对象生成
        # order_string
        # 构造支付地址
        # 返回响应

        try:
            user = request.user
        except Exception:
            raise Exception('用户未登录')

        try:
            order = OrderInfo.objects.filter(order_id=order_id,
                                             user=user,
                                             status = OrderInfo.ORDER_STATUS_ENUM['UNPAID'])
        except OrderInfo.DoesNotExist:
            return Response({'message':'订单不存在或订单数据出错鸟'},status=status.HTTP_400_BAD_REQUEST)

        alipay = Generate_alipay_handler()

        order_string = alipay.api_alipay_trade_page_pay(
            out_trade_no=order_id,
            total_amount=str(order[0].total_amount),
            subject= '订单支付',
            return_url='http://www.meiduo.site:8080/pay_success.html',
        )

        #构造前端需要请求的支付地址
        pay_url = settings.ALIPAY_URL + '?' + order_string

        return Response({'alipay_url':pay_url})


class OrdersPayResultView(APIView):

    def put(self,request):
        data = request.query_params.dict()
        signature = data.pop("sign")

        alipay = Generate_alipay_handler()
        success = alipay.verify(data, signature)
        if success:
            order_id = data.get('out_trade_no')
            payment_flow_id = data.get('trade_no')
            Payment.objects.create(
                order_id = order_id,
                trade_id = payment_flow_id
            )
            OrderInfo.objects.filter(order_id=order_id).update(status=OrderInfo.ORDER_STATUS_ENUM['UNSEND'])
            return Response({'trade_id':payment_flow_id})
        else:
            return Response({'message':'支付信息错误'},status=status.HTTP_400_BAD_REQUEST)

